using System.Diagnostics;
using Microsoft.AspNetCore.Mvc;
using StudentManagement.Models;

namespace StudentManagement.Controllers;

public class StudentsController : Controller
{
    // 引用数据库上下文
    private readonly StudentDbContext Db;
    // new无参的构造方法
    public StudentsController()
    {
        Db=new StudentDbContext();
    }
    // 查询
        public IActionResult Index(string KeyWord)
    {
        KeyWord=string.IsNullOrEmpty(KeyWord)?"":KeyWord.Trim();
        if(string .IsNullOrEmpty(KeyWord))
        {
        var list=Db.Students.ToList();
        return View(list);
        }
        var a=Db.Students.Where(x=>x.Name.Contains(KeyWord)).ToList();
        return View(a);

    }
   //删除 
    public IActionResult Delete(int id)
    {
        var a=Db.Students.FirstOrDefault(x=>x.Id==id);
        return View(a);
    }
    public IActionResult Deletes(int id)
    {
        var a=Db.Students.FirstOrDefault(x=>x.Id==id);
        if(a==null)
        {
            return NotFound();
        }
        Db.Students.Remove(a);
        Db.SaveChanges();
        return RedirectToAction("Index");
    }
    //修改 
    public IActionResult Edit(int id)
    {
        var a=Db.Students.FirstOrDefault(x=>x.Id==id);
        return View(a);
    }
    [HttpPost]
     public IActionResult Edit(Student input)
    {
        var a=Db.Students.FirstOrDefault(x=>x.Id==input.Id);
        if(a==null)
        {
            // NotFound【找不到】()
            return NotFound();
        }
         a.Name=input.Name;
         a.Age=input.Age;
         Db.SaveChanges();
        // Redirect(重定向)ToAction()
        return RedirectToAction("Index");
    }
   //新增 
    public IActionResult Add()
    {
        return View();
    }



    [HttpPost]
    public IActionResult Add(Student input)
    {
        Db.Students.Add(input);
        // SaveChanges【保存更改】()
        Db.SaveChanges();
        return RedirectToAction("Index");
    }
}